package com.wlcb.jpower.chat.task.reply;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wlcb.jpower.chat.entity.customer.TblCustomerMsg;
import com.wlcb.jpower.chat.service.SearchService;
import com.wlcb.jpower.chat.service.customer.CustomerMsgService;
import com.wlcb.jpower.constant.ChatConfigConstant;
import com.wlcb.jpower.constant.ChatConstant;
import com.wlcb.jpower.constant.DBConstant;
import com.wlcb.jpower.im.cache.ImChatRecordCache;
import com.wlcb.jpower.im.model.DataPacket;
import com.wlcb.jpower.module.common.utils.BeanUtil;
import com.wlcb.jpower.module.common.utils.Fc;
import com.wlcb.jpower.properties.JpowerChatProperties;
import com.wlcb.jpower.utils.RedisHelpUtils;
import com.wlcb.jpower.utils.WxMpInstance;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author: liwenfei
 * @version: v1.0
 * @time: 2021/4/21 9:05
 * @desc: 自动回复任务
 */
@Slf4j
@Component
public class AutoReply {
    @Autowired
    private CustomerMsgService customerMsgService;
    @Autowired
    private SearchService searchService;
    @Autowired
    private JpowerChatProperties properties;

    /**
     * 客服不在线 自动搜索语音识别结果 并发送给用户
     */
    @Scheduled(cron = "0 0/3 * * * ?")
    public void reply() {
        if (!properties.getAutoBaiduReply()) {
            return;
        }


        RedisHelpUtils.RedisLock redisLock = RedisHelpUtils.getRedisLock();
        String lockKey = "reply";
        boolean is = redisLock.tryLock(lockKey);
        if (is) {
            try {
                List<TblCustomerMsg> msgs = customerMsgService.list(new QueryWrapper<TblCustomerMsg>().lambda()
                        .in(TblCustomerMsg::getStatus, DBConstant.CustomerMsgEnum.ACCESSED.getType(), DBConstant.CustomerMsgEnum.WAIT_ACCESS.getType()));
                for (TblCustomerMsg msg : msgs) {
                    if (properties.getAutoBaiduReplyAppid() != null && properties.getAutoBaiduReplyAppid().length > 0 && !Fc.contains(properties.getAutoBaiduReplyAppid(), msg.getAppid())) {
                        continue;
                    }
                    ImChatRecordCache imChatRecordCache = ImChatRecordCache.getInstance(msg.getOpenid());
                    if (Fc.notNull(imChatRecordCache)) {
                        List<DataPacket> records = imChatRecordCache.getRecords();
                        if (Fc.notNull(records) && records.size() > 0) {
                            access(records, imChatRecordCache);
                        }
                    }
                }
            } catch (WxErrorException e) {
                e.printStackTrace();
            } finally {
                redisLock.runlock(lockKey);
            }
        }

    }

    public void access(List<DataPacket> records, ImChatRecordCache recordCache) throws WxErrorException {
        //最后一条数据
        DataPacket dataPacket = records.get(records.size() - 1);
        if (ChatConstant.MessageTypeEnum.TEXT.type.equals(dataPacket.getType()) && dataPacket.getAction().intValue() == ChatConstant.ChatActionEnum.CUSTOMER_VOICE.getType()) {
            if (System.currentTimeMillis() - dataPacket.getDate() >= 1000 * 60 * 3) {
                String query = searchService.query(dataPacket.getContent());
                if (Fc.isNotBlank(query)) {
                    WxMpInstance.getWxMp().switchoverTo(dataPacket.getAppId()).getKefuService()
                            .sendKefuMessage(WxMpKefuMessage.TEXT().toUser(recordCache.getUserId()).content(query).build());
                    DataPacket copy = BeanUtil.copyProperties(dataPacket, DataPacket.class);
                    copy.setAction(ChatConstant.ChatActionEnum.CUSTOMER_USER_MESSAGE.type);
                    copy.setReceiveType(ChatConfigConstant.UserType.OTHER);
                    copy.setSendType(ChatConfigConstant.UserType.CUSTOMER);
                    copy.setContent(query);
                    recordCache.setRecords(copy);
                }
            }
        }
    }

}
